#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import config as c
from gitlab_map import site_map
import os
import re
from ftplib import FTP

root_path = c.local_www_path
# tpl_file_path = '/common/models/WorldpayLog.php'
tpl_file_path = ''

pattern1 = ""
new_str1 = ''' '''

pattern2 = ""
new_str2 = ''' '''

def alter(file, new_str, pattern):
    try:
        with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
            content = f1.read()
            match_ret = re.search(pattern, content)
            flag = False

            if match_ret is None:
                print(file + ' ***** 异常: None,未匹配到 *****')
            else:
                text = re.sub(pattern, new_str, content)
                f2.write(text)
                flag = True

        if flag == True:
            os.remove(file)
            os.rename("%s.bak" % file, file)
            print(file + ' >>> 已完成')
    except Exception as e:
        print(file + ' ***** 异常 ***** >>> ' + str(e))

# def ftp_connect(host, port, username, password):
#     f = FTP()
#     f.connect(host, port)
#     f.login(username, password)
#     return f
#
# def git_master(dir_repo, commit_msg, root_path):
#     repo = git.Repo(root_path + dir_repo)
#     print('>> start git...')
#     try:
#         repo.git.pull()
#     except Exception as e:
#         print('     ⬇⬇⬇   { Error }   ⬇⬇⬇    ️')
#         print(e)
#         print('     ⬆⬆⬆ ️ { Error }   ⬆⬆⬆    ️')
#         print('****************************** end\n')
#     else:
#         if repo.is_dirty():
#             status = repo.git.status()
#             regex = re.compile("modified:\s\s\s(.*?)\n").findall(status)
#             repo.git.add('-u')
#             repo.git.commit('-m', commit_msg)
#             # repo.git.push()
#             print('>> git commit finished.')
#             return regex
#         else:
#             print('>> No modified files.')
#             print('****************************** end')
#             print(' ')


if __name__ == "__main__":
    for i in c.dirname_list:
        i = i.lower()
        dirname = site_map[i][35:][:-4].lower()
        project_path = root_path + dirname
        tpl = project_path + tpl_file_path
        alter(tpl, new_str1, pattern1)
        # alter(tpl, new_str2, pattern2)